package com.fujin.gulimall.member.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fujin.common.Vo.SocialUser;
import com.fujin.common.utils.HttpUtils;
import com.fujin.gulimall.member.Exception.PhoneExistException;
import com.fujin.gulimall.member.Exception.UserNameExistException;
import com.fujin.gulimall.member.Vo.RegisterVo;
import com.fujin.gulimall.member.Vo.loginVo;
import com.fujin.gulimall.member.dao.MemberLevelDao;
import com.fujin.gulimall.member.entity.MemberLevelEntity;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fujin.common.utils.PageUtils;
import com.fujin.common.utils.Query;

import com.fujin.gulimall.member.dao.MemberDao;
import com.fujin.gulimall.member.entity.MemberEntity;
import com.fujin.gulimall.member.service.MemberService;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Autowired
    private MemberLevelDao memberLevelDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void regist(RegisterVo registerVo) throws PhoneExistException,UserNameExistException{
        MemberEntity memberEntity = new MemberEntity();

        //设置会员的默认等级，从MemberLevel中获取默认等级
        MemberLevelEntity memberLevelEntity = memberLevelDao.Getlever();
        memberEntity.setLevelId(memberLevelEntity.getId());

        //保存之前需要判断用户名和手机号是否已经存在,使用异常机制
        //将异常往上抛出，controller层使用trycatch捕获
        cheCkPhone(registerVo.getPhone());
        cheCkUserName(registerVo.getUserName());

        memberEntity.setUsername(registerVo.getUserName());
        memberEntity.setMobile(registerVo.getPhone());

        //设置密码，但在设置进去之前需要进行加密，不能直接明文存入数据库中
        //BCryptPasswordEncoder类似于一个MD5+盐的操作，这样盐就像是存好的一堆值，随机拿出一个进行加密
        //登录校验的时候可以使用passwordEncoder.matches()方法将明文密码和加密的进行对比
        //返回true说明正确。反之错误
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String encode = passwordEncoder.encode(registerVo.getPassword());
        memberEntity.setPassword(encode);

        this.baseMapper.insert(memberEntity);
    }

    /**
     * 校验手机号是否存在
     * @param phone
     */
    @Override
    public void cheCkPhone(String phone) throws PhoneExistException{
        Integer mobile = this.baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("mobile", phone));
        if (mobile > 0){
            throw new PhoneExistException();
        }
    }

    /**
     * 校验用户名是否存在
     * @param UserName
     */
    @Override
    public void cheCkUserName(String UserName) throws UserNameExistException{
        Integer mobile = this.baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("username", UserName));
        if (mobile > 0){
            throw new UserNameExistException();
        }
    }

    @Override
    public MemberEntity login(loginVo loginVo) {
        //根据用户名或电话号码查询用户是否存在
        MemberEntity memberEntity = this.baseMapper.selectOne(new QueryWrapper<MemberEntity>()
                .eq("username", loginVo.getUserName()).or()
                .eq("mobile", loginVo.getUserName()));

        if (memberEntity == null){
            //说明用户不存在
            return null;
        }else {
            //用户存在、判断密码是否正确
            //注册的使用通过BCryptPasswordEncoder进行一个加密
            //登录的时候就需要passwordEncoder.matches()方法将传入的明文密码和加密的进行对比
            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            boolean matches = passwordEncoder.matches(loginVo.getPassWord(), memberEntity.getPassword());
            if (matches){
                //密码正确
                return memberEntity;
            }else {
                //密码错误
                return null;
            }
        }
    }

    /**
     * 微博社交登录
     * @param socialUser
     * @return
     */
    @Override
    public MemberEntity login(SocialUser socialUser) {
        //根据uid判断该用户是否注册过
        String uid = socialUser.getUid();
        MemberEntity memberEntity = this.baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("social_uid", uid));

        if (memberEntity == null){
            //为空说明没注册过，此时就进行注册操作
            MemberEntity entity = new MemberEntity();

            //构建请求uid参数
            HashMap<String, String> map = new HashMap<>();
            map.put("access_token",socialUser.getAccessToken());
            map.put("uid",socialUser.getUid());
            //调用微博提供接口，获取微博账号的个人信息
            try {
                HttpResponse response = HttpUtils.doGet("https://api.weibo.com", "/2/users/show.json", "get", new HashMap<>(), map);
                if (response.getStatusLine().getStatusCode() == 200){
                    //查询成功
                    String json = EntityUtils.toString(response.getEntity());
                    JSONObject jsonObject = JSON.parseObject(json);
                    String name = jsonObject.getString("name");
                    String city = jsonObject.getString("city");
                    String profile_image_url = jsonObject.getString("profile_image_url");
                    entity.setCity(city);//所在城市
                    entity.setNickname(name);//名称
                    entity.setHeader(profile_image_url);//头像地址
                    entity.setLevelId(1L);//默认等级
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            //放在trycatch外面是因为就算调用接口出现问题还是需要创建账号 设置微博登录token、uid信息
            entity.setAccessToken(socialUser.getAccessToken());
            entity.setSocialUid(socialUser.getUid());
            entity.setExpiresIn(socialUser.getExpiresIn());
            this.baseMapper.insert(entity);
            return entity;

        }else {
            //不为空，进行登录操作，更新token信息
            MemberEntity update = new MemberEntity();
            update.setId(memberEntity.getId());
            update.setAccessToken(socialUser.getAccessToken());
            update.setExpiresIn(socialUser.getExpiresIn());

            this.baseMapper.updateById(update);

            memberEntity.setAccessToken(socialUser.getAccessToken());
            memberEntity.setExpiresIn(socialUser.getExpiresIn());
            return memberEntity;
        }
    }

}